class Solution
{
public:
    int robotSim(vector<int> &commands, vector<vector<int>> &obstacles)
    {
        unordered_set<int> obs;
        for (auto &ob : obstacles)
        {
            obs.insert(ob[0] + ob[1] * 30004);
        }

        const vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int direction = 0;
        int maxDistance = 0;
        int x = 0;
        int y = 0;
        for (int command : commands)
        {
            if (command == -1)
            {
                direction = (direction + 1) % 4;
            }
            else if (command == -2)
            {
                direction = (direction + 3) % 4;
            }
            else
            {
                for (int step = 0; step < command; ++step)
                {
                    int nextX = x + directions[direction][0];
                    int nextY = y + directions[direction][1];
                    if (obs.count(nextX + nextY * 30004))
                    {
                        break;
                    }
                    x = nextX;
                    y = nextY;
                    maxDistance = max(maxDistance, x * x + y * y);
                }
            }
        }
        return maxDistance;
    }
};